/* 
 * File:   MathEdit.cpp
 * Author: user
 * 
 * Created on December 10, 2012, 3:12 PM
 */

#include "MathEdit.h"
#include <iostream>
#include <QFocusEvent>
#include <QKeyEvent>
#include <QStyleOptionFrameV2>
#include <QApplication>
#include <QtGui>

MathEdit::MathEdit(const QPoint &pos, QWidget * parent)
: QTextEdit(parent) {
    // setup for one line edit
    setTabChangesFocus(true);
    setWordWrapMode(QTextOption::NoWrap);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    setFixedHeight(sizeHint().height());
    // set its position on its parent
    move(pos);
    // set to transparent background
    viewport()->setAutoFillBackground(false);
    // set the frame to nothing
    setFrameStyle(QFrame::NoFrame);
    // resize the input field
    adjustSize();


    QFont font;
    font.setFamily("Courier");
    font.setFixedPitch(true);
    font.setPointSize(10);

    setFont(font);

    highlighter = new Highlighter(document());

    // get the focus
    setFocus();
}

void MathEdit::focusOutEvent(QFocusEvent * event) {
    // make the MathItem delete its self if there is nothing in it
    if (toPlainText().trimmed().size() < 1) {
        setAttribute(Qt::WA_DeleteOnClose);
        close();
    }
    QTextEdit::focusOutEvent(event);
}

void MathEdit::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
        event->ignore();
    else
        QTextEdit::keyPressEvent(event);

    adjustSize();
}

QSize MathEdit::sizeHint() const {
    //    The following code did not seem to change the size so I left if out
    //    int h = document()->size().height();
    //    int w = document()->size().width() + 4;
    //    QStyleOptionFrameV2 opt;
    //    opt.initFrom(this);
    //    QSize si(w, h);
    //    QSize sii = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, si, this);

    document()->adjustSize();
    return QSize(document()->size().width() + 4, document()->size().height());
}